# -*- coding: UTF-8 -*-

from datetime import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger

__all__ = ['TagDepartment']

class TagDepartment(Base, SessionMixin):
    '''
    标签和公司信息的对应关系
    '''
    __tablename__ = "tag_department"
    tag_key = Column(String(256), nullable=False, comment='标签名字')
    tag_value = Column(String(256), nullable=False, comment='标签值')
    environment = Column(String(128), nullable=False, index=True, comment='环境')
    bill_class = Column(String(128), nullable=False, index=True, comment='资产归类')
    maintain_department = Column(String(128), nullable=False, index=True, comment='管理部门')
    belong_department = Column(JSON, nullable=False, comment='所属部门')
    job_number = Column(String(128), nullable=True, comment='关联工单号')
    applicant = Column(String(128), nullable=True, comment='资源申请人')
    owner = Column(String(128), nullable=True, comment='资源归属人')
    expire_time = Column(DateTime, nullable=True, comment="过期时间")
    update_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    comment = Column(String(256), nullable=True, comment='标签说明')



    __table_args__ = (
        Index('idx_tag_department_tag_key_tag_value', 'tag_key', 'tag_value', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )

    def __repr__(self):
        return f"<tag_department={self.maintain_department}:{self.belong_department}>"


    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }
        return result


    @classmethod
    def get_object_by_tag(cls, db: Session, tag_key: str, tag_value: str):
        object = db.query(cls).filter(
            cls.tag_key == tag_key,
            cls.tag_value == tag_value,
        ).first()
        return object


    @classmethod
    def get_object_info_by_tag(cls, db: Session, tag_key: str, tag_value: str):
        object = db.query(cls).filter(
            cls.tag_key == tag_key,
            cls.tag_value == tag_value,
        ).to_dict_first()
        return object


    # 删除一个标签所有的数据，重新同步账单时使用
    @classmethod
    def delete_tag_key(cls, db: Session, bill_cycle: str):
        db.query(cls).filter(
            cls.bill_cycle == bill_cycle
        ).delete()
        db.commit()